package com.wangjiang.controller;

import com.wangjiang.model.UserModel;
import com.wangjiang.rest.ResultGenerator;
import com.wangjiang.rest.entity.Result;
import com.wangjiang.service.UserService;
import com.wangjiang.service.shiro.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    private ShiroService shiroService;

    @ResponseBody
    @PostMapping("/add")
    public int addUser(UserModel user) {
        return userService.addUser(user);
    }

    @ResponseBody
    @GetMapping("/all")
    public Object findAllUser(
            @RequestParam(name = "pageNum", required = false, defaultValue = "1")
                    int pageNum,
            @RequestParam(name = "pageSize", required = false, defaultValue = "10")
                    int pageSize
    ) {
        return userService.findAllUser(pageNum,pageSize);
    }


    @PostMapping("/login")
    public Result doLogin(String username, String password) {

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            token.clear();
            return ResultGenerator.genFailResult("登录失败，用户名或密码错误！");
        }
        return ResultGenerator.genSuccessResult("登录成功");
    }

    @PostMapping("/register")
    public Result register(String username, String password) {

        UserModel user = shiroService.addUser(username, password);
        return ResultGenerator.genSuccessResult(user).setMessage("注册成功");
    }

}
